<template>
    <view class="page-box">
        <header class="header"></header>
        <view class="section">
            <view class="entrance row verCenter">
                <view class="text">
                    <view class="row">
                        <text class="t1">您即将开启的是<br />汽车金融专业之路</text>
                    </view>
                </view>
                <view class="pic">
                    <image src="../../static/b2.png" mode="aspectFill"></image>
                </view>
            </view>
            <view class="btn row rowCenter verCenter" @click="open()">一键开启</view>
            <view class="list column">
                <view class="box" v-for="(item,index) in KnowledgeClass" :key="index" @click="toUrl(item.id,item.class_name)">
                    <view class="title">{{item.class_name}}</view>
                    <view class="desc">{{item.class_des}}</view>
                </view>
            </view>
        </view>
        <!--产品选中-->
        <uni-popup ref="popup" background-color="#ffffff" border-radius="20rpx">
            <view class="popup-content">
                <view class="select-type column">
                    <text class="title">请选择开启类型</text>
                    <view class="box row rowCenter verCenter" @click="selectChange(index)" v-for="(item,index) in list" :key="index">{{item.name}}&nbsp;&nbsp;￥{{item.price}}</view>
                </view>
            </view>
        </uni-popup>
        <!-- 支付弹窗 -->
        <uni-popup ref="popupPay" background-color="#fff" borderRadius="20rpx 20rpx 20rpx 20rpx">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column rowCenter verCenter">
                    <view class="ico">
                        <image src="../../static/pay.png" mode="aspectFill"></image>
                    </view>
                    <view class="row">
                        <text class="t2">请支付</text>
                        <text class="t3">{{list[index].price}}元</text>
                        <text class="t2">开启汽车金融专业之路</text>
                    </view>
                    <view class="price row rowCenter verCenter">￥{{list[index].price}}</view>
                    <view class="pay row rowCenter verCenter" @click="addKnowledgePayOrder()">去支付</view>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';

    export default {
        data() {
            return {
                list: [{ name: '月卡', price: 0 }, { name: '季卡', price: 0 }, { name: '年卡', price: 0 }],
                index: 0,
                KnowledgeClass: [],
                is_pay: '',
                pay_money_type: ''
            };
        },
        onShow() {
            this.getData();
        },
        methods: {
            getData() {
                this.request(API.getKnowledgePayinfo, 'GET', {}, false).then(res => {
                    if (res.code === 0) {
                        this.list[0].price = res.data.month_pay_money;
                        this.list[1].price = res.data.quarter_pay_money;
                        this.list[2].price = res.data.year_pay_money;
                        this.is_pay = res.data.is_pay;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
                this.request(API.getKnowledgeClass, 'GET', {}, false).then(res => {
                    if (res.code === 0) {
                        this.KnowledgeClass = res.data.data;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            toUrl(id, class_name) {
                //是否有权限查看
                if (this.is_pay == 1) {
                    uni.navigateTo({
                        url: `/pages/index/newsDetail?class_id=${id}&class_name=${class_name}`
                    })
                } else {
                    this.open();
                }
            },
            open() {
                this.$refs.popup.open('center');
            },
            selectChange(index) {
                this.index = index;
                this.pay_money_type = Number(index) + 1;
                this.$refs.popupPay.open('center');
            },
            close() {
                this.$refs.popupPay.close();
            },
            /**
             * 创建支付订单
             */
            addKnowledgePayOrder() {
                this.request(API.addKnowledgePayOrder, 'POST', { pay_money_type: this.pay_money_type }, true).then(res => {
                    if (res.code === 0) {
                        this.payToDoV2(res.data.pay_id);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 支付唤起操作
             */
            payToDoV2(pay_id) {
                this.request(API.payToDoV2, 'POST', { pay_id: pay_id }, true).then(res => {
                    if (res.code === 0) {
                        this.initWeixinPay(res.data, pay_id);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 初始化微信支付
             * @param {Object} payParams 支付参数
             * @param {String} pay_id 支付ID
             */
            initWeixinPay(payParams, pay_id) {
                const onBridgeReady = () => {
                    WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
                        if (res.err_msg === "get_brand_wcpay_request:ok") {
                            this.close();
                            // 支付成功，开始轮询支付结果
                            this.startPollingPayResult(pay_id);
                        } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
                            // 用户取消支付
                            uni.showToast({
                                title: '支付已取消',
                                icon: 'none'
                            });
                        } else {
                            // 其他情况，可能是支付失败或未知错误
                            uni.showToast({
                                title: '支付失败，请重试',
                                icon: 'none'
                            });
                        }
                    });
                };

                if (typeof WeixinJSBridge == "undefined") {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    } else if (document.attachEvent) {
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                } else {
                    onBridgeReady();
                }
            },
            /**
             * 开始轮询支付结果
             * @param {String} pay_id 支付ID
             */
            startPollingPayResult(pay_id) {
                let pollCount = 0;
                const maxPollCount = 100;
                const pollInterval = 1000;

                const pollPayResult = async () => {
                    while (pollCount < maxPollCount) {
                        await new Promise(resolve => setTimeout(resolve, pollInterval));

                        try {
                            const result = await this.getPayOrderInfoV2(pay_id);
                            if (result.code === 0 && result.data.pay_status === 1) {
                                // 支付成功，显示提示并处理后续逻辑
                                uni.showToast({
                                    title: '支付成功',
                                    icon: 'success'
                                });
                                setTimeout(() => {
                                    this.close();
                                    this.$refs.popup.close();
                                    this.getData();
                                }, 2000);
                                return true;
                            }
                        } catch (error) {
                            console.error('查询支付结果出错:', error);
                        }
                        pollCount++;
                    }
                    return false;
                };

                pollPayResult().then(success => {
                    if (!success) {
                        console.log('支付结果查询超时');
                        uni.showToast({
                            title: '支付查询超时，请稍后检查订单状态',
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 支付成功后定时任务查询支付结果
             * @param {Object} pay_id
             * @returns {Promise} 返回请求结果
             */
            getPayOrderInfoV2(pay_id) {
                return this.request(API.getPayOrderInfoV2, 'POST', { pay_id: pay_id }, true);
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/index/news.scss';
</style>